import { getToken, setToken, removeToken } from '@/utils/auth';
import router, { resetRouter } from '@/router';
import * as userApi from '@/api/user';
// import { get_company_info } from '@/api/enterprise';
import setting from '@/settings.js';
const state = {
  token: getToken(),
  userInfo: {},
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissions: [],
  companyInfo: {}
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_COMPANYINFO: (state, companyInfo) => {
    state.companyInfo = companyInfo;
  }
};

const actions = {
  // user login
  async login({ commit }, userInfo) {
    try {
      const response = await userApi.login(userInfo);
      if (response) {
        const { data } = response;
        const token = setting.jwtPerfix + data;
        commit('SET_TOKEN', token);
        setToken(token);
        return true;
      }
    } catch (error) {
      console.error(error);
      throw error;
    }
  },

  async permission({ commit }, state) {
    try {
      const [userPermission, userRoles, userInfo] = await Promise.all([
        userApi.get_user_permission(),
        userApi.get_user_roles(),
        userApi.get_user_info()
        // get_company_info()
      ]);
      const permissions = userPermission.data.reduce((init, cur) => {
        init.push(cur.permission);
        return init;
      }, []);
      const roles = userRoles.data.reduce((init, cur) => {
        init.push(cur.role);
        return init;
      }, []);
      const roleNames = userRoles.data.reduce((init, cur) => {
        init.push(cur.roleName);
        return init;
      }, []);
      const user = userInfo.data;
      if (!roles.length) {
        roles.push('visitor');
      }
      if (!user.avatar) {
        user.avatar = '/images/avatar.gif';
      }
      user.roles = roles;
      user.roleNames = roleNames;
      user.permissions = permissions;
      // user.companyInfo = companyInfo.data;
      commit('SET_ROLES', roles);
      commit('SET_PERMISSIONS', permissions);
      commit('SET_USERINFO', user);
      // commit('SET_COMPANYINFO', companyInfo.data);
    } catch (error) {
      throw new Error(error);
    }
  },

  // user logout
  logout({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resetRouter();
      resolve();
      dispatch('tagsView/delAllViews', null, { root: true });
    });
  },

  // remove token
  resetToken({ commit, dispatch }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token';

      commit('SET_TOKEN', token);
      setToken(token);

      const { roles } = await dispatch('getInfo');

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true });

      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
